package com.it.system.searchservice.service.Impl;

import com.alibaba.fastjson.JSON;
import com.it.system.educommonapi.entity.Course;
import com.it.system.searchservice.dao.ElasticsearchDAO;
import com.it.system.searchservice.entity.ElasticsearchEntity;
import com.it.system.searchservice.entity.PageEntity;
import com.it.system.searchservice.entity.ResponseResult;
import com.it.system.searchservice.feign.CourseFeignClient;
import com.it.system.searchservice.service.CourseIndexService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程索引操作的实现类
 */
@Service
public class CourseIndexServiceImpl implements CourseIndexService {

    public static final String INDEX_NAME = "course";

    @Resource
    private ElasticsearchDAO dao;
    
    @Resource
    private CourseFeignClient courseFeignClient;
    
    /**
     * 初始化课程操作
     */
    @Override
    public void initCourseIndex() throws IOException {
        //判断索引是否存在
        if(dao.existIndex(INDEX_NAME)){
            //存在就删除
            dao.deleteIndex(INDEX_NAME);
        }
        
        //创建索引
        dao.createIndex(INDEX_NAME);
        
        //从课程服务获取课程数据
        ResponseResult<List<Course>> courseList = courseFeignClient.getAllCourse();
        if(courseList.getCode()==200 && courseList.getData()!=null){
            dao.importCourseData(INDEX_NAME,courseList.getData());
            System.out.println("课程索引初始化成功");
        }
    }

    @Override
    public PageEntity searchCourse(Map<String, String> map) throws IOException {
      long current=0,size=10;
      if(StringUtils.hasText(map.get("current"))){
          current=Long.parseLong(map.get("current"));
      }
      if (StringUtils.hasText(map.get("size"))){
          size=Long.parseLong(map.get("size"));
      }
      Map<String,String> search=new HashMap<>();
      if(StringUtils.hasText(map.get("search"))){
          search= JSON.parseObject(map.get("search"),Map.class);
      }
      Map<String,String> sort=new HashMap<>();
      if(StringUtils.hasText(map.get("sort"))){
          sort= JSON.parseObject(map.get("sort"),Map.class);
      }
      return dao.search(INDEX_NAME,current,size,search,sort,Course.class);
    }

    @Override
    public void saveCourse(Course course) throws IOException {
        dao.saveOrUpdate(INDEX_NAME,new ElasticsearchEntity(String.valueOf(course.getId()),course));
    }

    @Override
    public void removeCourse(String id) throws IOException {
        dao.deleteById(INDEX_NAME,id);
    }
}
